const { Controller } = require('egg');

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const body = ctx.request.body;
    ctx.validate(
      {
        email: 'email',
        password: 'password',
      },
      body
    );
    const userService = ctx.service.user;
    const user = await userService.findByEmail(body.email);
    if (!user) {
      ctx.throw(422, '用户不存在');
    }
    if (body.password !== user.password) {
      ctx.throw(422, '密码不正确');
    }
    const token = this.service.user.createToken({
      userId: user.id,
    });

    ctx.body = ctx.helper.responseSucceed({ data: {
      email: user.email,
      token,
      username: user.username,
    } });
  }

  async logout() {
    const { ctx } = this;
    const userService = ctx.service.user;
    const token = ctx.headers.authorization;
    userService.addTokenBlacklist(token);
    ctx.body = ctx.helper.responseSucceed({ msg: '退出登录成功！' });
  }
}

module.exports = UserController;
